<template>
  <div class="my-csign-view">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="par" label-width="80px" inline>
        <el-form-item label="患者姓名">
          <el-input v-model="par.Name" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="签约时间">
          <el-date-picker
            v-model="par.BeginTime"
            type="date"
            placeholder="开始时间"
            value-format="YYYY-MM-DD"
          />
          <span style="margin: 0 10px">至</span>
          <el-date-picker
            v-model="par.EndTime"
            type="date"
            placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ShowCsign">查询</el-button>
          <el-button @click="clearCsign">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" @click="OpenAddCsignList">
        <i class="el-icon-plus"></i> 新增签约
      </el-button>
      <div class="view-toggle">
        <el-button 
          :type="viewType === 'card' ? 'primary' : ''" 
          @click="viewType = 'card'"
        >
          <i class="el-icon-menu"></i> 卡片视图
        </el-button>
        <el-button 
          :type="viewType === 'table' ? 'primary' : ''" 
          @click="viewType = 'table'"
        >
          <i class="el-icon-tickets"></i> 列表视图
        </el-button>
      </div>
    </div>

    <!-- 卡片视图 -->
    <div v-if="viewType === 'card'" class="card-container">
      <div 
        v-for="item in tableData" 
        :key="item.cSignId" 
        class="patient-card"
      >
        <div class="card-header">
          <div class="patient-name">{{ item.recordName }}</div>
          <div class="patient-gender-age">
            <el-tag 
              :type="(item.recordSex == 1 || item.recordSex == '男') ? 'primary' : 'success'" 
              effect="dark"
            >
              {{ (item.recordSex == 1 || item.recordSex == '男') ? '男' : '女' }} {{ item.recordAge }}岁
            </el-tag>
          </div>
        </div>
         
        <div class="card-actions">
          <el-button 
            plain 
            size="small" 
            @click="DelCsignInfo(item.cSignId)"
            class="terminate-btn"
          >
            <i class="el-icon-delete"></i> 解约
          </el-button>
          
          <el-button 
            plain 
            size="small" 
            @click="handleAdjust(item)"
            class="adjust-btn" 
          >
            <i class="el-icon-edit"></i> 调整
          </el-button>

         

          <el-button 
            plain 
            size="small" 
            @click="UpSCsignInfo(item)"
            class="renew-btn"
          >
            <i class="el-icon-refresh"></i> 续签
          </el-button>

          <el-button 
            plain 
            size="small" 
            @click="UpText"
            class="renew-btn"
          >
            <i class="el-icon-refresh"></i> 详情
          </el-button>
        </div>
        
        <div class="card-tags">
          <el-tag 
            v-for="tag in (item.tags || [item.cSignManage])" 
            :key="tag" 
            size="small" 
            effect="light"
            class="disease-tag"
          >
            {{ tag }}
          </el-tag>
        </div>
        
        <div class="card-info">
          <div class="info-row">
            <i class="el-icon-phone-outline info-icon"></i>
            <span>联系电话：{{ item.recordPhone }}</span>
          </div>
          <div class="info-row">
            <i class="el-icon-document info-icon"></i>
            <span>身份证号：{{ maskIdcard(item.recordIdcard) }}</span>
          </div>
          <div class="info-row">
            <i class="el-icon-date info-icon"></i>
            <span>签约时间：{{ formatDate(item.cSignBegin) }}</span>
          </div>
          <div class="info-row">
            <i class="el-icon-circle-close info-icon"></i>
            <span>结束时间：{{ formatDate(item.cSignEnd) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-else class="table-container">
      <el-table 
        :data="tableData" 
        style="width: 100%"
        :row-class-name="tableRowClassName"
        empty-text="暂无数据"
      >
        <el-table-column prop="recordName" label="姓名" width="100" />
        <el-table-column prop="recordSex" label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag 
              :type="(scope.row.recordSex == 1 || scope.row.recordSex == '男') ? 'primary' : 'success'" 
              effect="light"
              class="sex-tag"
            >
              {{ (scope.row.recordSex == 1 || scope.row.recordSex == '男') ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recordAge" label="年龄" width="80" align="center" />
        <el-table-column prop="cSignManage" label="疾病标签" width="120" />
        <el-table-column prop="recordPhone" label="联系电话" width="150" />
        <el-table-column prop="recordIdcard" label="身份证号" width="180">
          <template #default="scope">
            {{ maskIdcard(scope.row.recordIdcard) }}
          </template>
        </el-table-column>
        <el-table-column prop="cSignBegin" label="签约时间" width="150" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.cSignBegin) }}
          </template>
        </el-table-column>
        <el-table-column prop="cSignEnd" label="结束时间" width="150" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.cSignEnd) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button 
              plain 
              size="small" 
              @click="DelCsignInfo(scope.row.cSignId)"
              class="terminate-btn"
            >
              <i class="el-icon-delete"></i> 解约
            </el-button>
            <el-button 
              plain 
              size="small" 
              @click="handleAdjust(scope.row)"
              class="adjust-btn"
            >
              <i class="el-icon-edit"></i> 调整
            </el-button>

            <!-- 使用共用的弹出框组件 -->
            <SharedSignDialog
              v-model:visible="UpCsignList"
              dialog-type="edit"
              :patient-data="currentPatientData"
              @close="UpCsignList = false"
              @success="handleUpdateSuccess"
            />

            <el-button 
              plain 
              size="small" 
              @click="UpSCsignInfo(scope.row)"
              class="renew-btn"
            >
              <i class="el-icon-refresh"></i> 续签
            </el-button>

            <el-button 
              plain 
              size="small" 
              @click="UpText"
              class="renew-btn"
            >
              <i class="el-icon-refresh"></i> 详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
<!-- 使用共用的弹出框组件 -->
          <SharedSignDialog
            v-model:visible="UpCsignList"
            :dialog-type="dialogType"
            :patient-data="currentPatientData"
            @close="UpCsignList = false"
            @success="handleUpdateSuccess"
          />
    <!-- 新增签约弹窗 -->
    <el-dialog 
      v-model="AddCsignList" 
      title="慢性病患者签约" 
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AddCS @close="AddCsignList = false" />
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="par.Pageindex"
        v-model:page-size="par.Pagesize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="par.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize } from 'element-plus';
import AddCS from '@/views/Doctors Desktop Version/ChronicSign/AddCSignview.vue';
import SharedSignDialog from '@/views/Doctors Desktop Version/ChronicSign/SharedSignDialog.vue';
import axios from 'axios';
import { Read, Write } from '@/Http/Axios';

// 响应式变量
const AddCsignList = ref<boolean>(false);
const UpCsignList = ref<boolean>(false);
const currentPatientData = ref<any>(null);
const dialogType = ref<string>('edit'); // 添加dialogType响应式变量

// 组件初始化
onMounted(() => {
  ShowCsign();
});

// 新增签约弹窗控制
const OpenAddCsignList = () => {
  AddCsignList.value = true;
};

// 视图类型控制
const viewType = ref<string>('card');

// 查询重置
const clearCsign = () => {
  par.Name = '';
  par.BeginTime = null;
  par.EndTime = null;
  ShowCsign();
};

// 患者数据
const tableData = ref<any[]>([]);

// 查询参数
const par = reactive<SearchParams>({
  Pageindex: 1,
  Pagesize: 10,
  totalCount: 0,
  totalPage: 0,
  Name: '',
  BeginTime: null,
  EndTime: null,
});

const handleAdjust = (row: PatientRecord) => {
  console.log('调整操作:', row);
  // 设置当前患者数据
  currentPatientData.value = row;
  // 设置对话框类型为编辑
  dialogType.value = 'edit';
  // 显示调整签约对话框
  UpCsignList.value = true;
};

// 续签操作
const UpSCsignInfo = (row:any) => {
  // 设置当前患者数据
  currentPatientData.value = row;
  // 设置对话框类型为续签
  dialogType.value = 'renew';
  // 显示对话框
  UpCsignList.value = true;
}

const UpText = () => {
  location.href = '/GotCsignview';
}

// 处理更新成功事件
const handleUpdateSuccess = () => {
  // 可以在这里添加更新成功后的处理逻辑，比如刷新表格数据
  console.log('签约信息更新成功');
  ShowCsign(); // 刷新表格数据
}

//删除
const DelCsignInfo = (cSignId:any) => {
  ElMessageBox.confirm(
    '确认解约该患者吗？',
    '警告!',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete('http://localhost:5203/api/Managment/DelCsign',{params:{cSignId:cSignId}}).then(() => {
        ElMessage.success('解约成功');
        ShowCsign();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '该操作已取消',
      })
    })
}


// 定义类型接口
interface PatientRecord {
  recordName: string;
  recordSex: number | string;
  recordAge: number;
  cSignManage: string;
  recordPhone: string;
  recordIdcard: string;
  cSignBegin: string | Date;
  cSignEnd: string | Date;
  tags?: string[];
}

interface SearchParams {
  Pageindex: number;
  Pagesize: number;
  totalCount: number;
  totalPage: number;
  Name: string;
  BeginTime: string | Date | null;
  EndTime: string | Date | null;
}

/**
 * 处理操作按钮点击事件
 * @param action 操作类型
 * @param item 患者数据
 */
const handleAction = (action: string, item: PatientRecord): void => {
  switch (action) {
    case 'terminate':
      ElMessage.warning(`确认要与患者 ${item.recordName} 解约吗？`);
      // 实现解约逻辑
      break;
    case 'adjust':
      ElMessage.info(`正在调整患者 ${item.recordName} 的签约信息`);
      // 实现调整逻辑
      break;
    case 'renew':
      ElMessage.success(`正在为患者 ${item.recordName} 办理续签`);
      // 实现续签逻辑
      break;
  }
};

/**
 * 格式化日期
 * @param date 日期字符串或日期对象
 * @returns 格式化后的日期字符串
 */
const formatDate = (date: string | Date | undefined): string => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
/**
 * 身份证号脱敏
 * @param idcard 身份证号
 * @returns 脱敏后的身份证号
 */
const maskIdcard = (idcard: string | undefined): string => {
  if (!idcard || idcard.length < 10) return idcard || '';
  return idcard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2');
};

/**
 * 获取患者数据
 */
const ShowCsign = async (): Promise<void> => {
  try {
    // 实际项目中使用API获取数据
    const response = await Read.get('http://localhost:5108/api/Manager/ShowCsign', { params: par });
    tableData.value = response.data.data.data || [];
    par.totalCount = response.data.data.totalCount || 0;
    par.totalPage = response.data.data.totalPage || 0;
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
    
    // 如果API失败，使用模拟数据
    getMockData();
  }
};

/**
 * 获取模拟数据
 */
const getMockData = (): void => {
  par.totalCount = tableData.value.length;
  par.totalPage = Math.ceil(par.totalCount / par.Pagesize);
};

/**
 * 处理每页显示数量变化
 * @param val 每页显示数量
 */
const handleSizeChange = (val: number): void => {
  par.Pagesize = val;
  ShowCsign();
};

/**
 * 处理当前页变化
 * @param val 当前页码
 */
const handleCurrentChange = (val: number): void => {
  par.Pageindex = val;
  ShowCsign();
};

/**
 * 表格行样式函数
 * @param rowIndex 行索引
 * @returns 样式类名
 */
const tableRowClassName = ({ rowIndex }: { rowIndex: number }): string => {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};
</script>

<style scoped>
.my-csign-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.action-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-toggle {
  display: flex;
  gap: 10px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

/* 患者卡片 */
.patient-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.patient-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.patient-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 卡片操作按钮组 */
.card-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

/* 卡片标签 */
.card-tags {
  margin-bottom: 15px;
}

.disease-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.card-info .info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #666;
}

.info-icon {
  margin-right: 8px;
  color: #409eff;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.sex-tag {
  width: 50px;
  text-align: center;
}

.terminate-btn {
  color: #f56c6c;
  border-color: #f56c6c;
}

.terminate-btn:hover {
  background: #f56c6c;
  color: white;
  font-weight: 600;
  border-bottom: none;
}

.adjust-btn {
  color: #409eff;
  border-color: #409eff;
}

.adjust-btn:hover {
  background: #409eff;
  color: white;
}

.renew-btn {
  color: #67c23a;
  border-color: #67c23a;
}

.renew-btn:hover {
  background: #67c23a;
  color: white;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding: 16px 24px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-row-even {
  background-color: #fafafa;
}

.table-row-odd {
  background-color: #ffffff;
}
</style>